package com.mflex.flexwi;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.collection.SimpleArrayMap;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.dou361.dialogui.DialogUIUtils;
import com.king.zxing.CameraScan;
import com.mflex.flexwi.adapter.SignAdapter;
import com.mflex.flexwi.bean.SignItem;
import com.mflex.flexwi.fragment.SignDataFragment;
import com.mflex.flexwi.util.CommonUtil;
import com.mflex.flexwi.util.SoapObjectUtil;
import com.mflex.flexwi.util.WebServiceUtil;
import com.rosefinches.smiledialog.SmileDialog;
import com.rosefinches.smiledialog.SmileDialogBuilder;
import com.rosefinches.smiledialog.enums.SmileDialogType;

import org.apache.commons.lang3.StringUtils;
import org.ksoap2.serialization.SoapObject;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static android.app.DatePickerDialog.OnDateSetListener;

public class SignQueryActivity extends BaseActivity {
    private static String userNmae;
    private static String userPassword;
    private static String webServiceUrl;
    private static String docName;
    private static String docNumber;
    private static List<SignItem> signList;
    private SignDataFragment mSignDataFragment;

    private static int yearSart = -1;
    private static int monthStart = -1;
    private static int dayStart = -1;

    private static int yearEnd = -1;
    private static int monthEnd = -1;
    private static int dayEnd = -1;

    private LinearLayout llSearch;
    private LinearLayout linearLayout8;
    private TextView textView1;
    private LinearLayout linearLayout2;
    private TextView lblEmployeeId;
    private EditText txtEmployeeId;
    private EditText txtLeaderId;
    private TextView lblDocNub;
    private EditText txtDocNub;
    private TextView lblDocName;
    private EditText txtDocName;
    private LinearLayout linearLayout3;
    private TextView lblStartTime;
    private EditText txtStartTime;
    private TextView lblEndTime;
    private EditText txtEndTime;
    private Button btnClear;
    private Button btnSerach;
    private Button btnClose;
    private ListView lvSign;

    private ImageButton imageButtonDocName;
    private ImageButton imageButtonDocNub;
    private ImageButton imageButtonEmployeeId;
    private ImageButton imageButtonStartTime;
    private ImageButton imageButtonEndTime;
    private ImageButton imageButtonLeaderId;

    public final int REQUEST_CODE_DOC_NAME = 1;
    public final int REQUEST_CODE_DOC_NUB = 2;
    public final int REQUEST_CODE_EMPLOYEE_ID = 3;
    public final int REQUEST_CODE_START_TIME = 4;
    public final int REQUEST_CODE_END_TIME = 5;
    public final int REQUEST_CODE_LEADER_ID = 6;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_query);

        if(CommonUtil.isTabletDevice(this)){
            int orientation=getResources().getConfiguration().orientation;
            if(orientation== Configuration.ORIENTATION_LANDSCAPE){
                setContentView(R.layout.activity_sign_query_h);
            }else if(orientation==Configuration.ORIENTATION_PORTRAIT){
                setContentView(R.layout.activity_sign_query_v);
            }
            imageButtonDocName = (ImageButton) findViewById(R.id.imageButtonDocName);
            imageButtonDocNub = (ImageButton) findViewById(R.id.imageButtonDocNub);
            imageButtonEmployeeId = (ImageButton) findViewById(R.id.imageButtonEmployeeId);
            imageButtonStartTime = (ImageButton) findViewById(R.id.imageButtonStartTime);
            imageButtonEndTime = (ImageButton) findViewById(R.id.imageButtonEndTime);
            imageButtonLeaderId = (ImageButton) findViewById(R.id.imageButtonLeaderId);

            imageButtonDocName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_DOC_NAME);
                }
            });
            imageButtonDocNub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_DOC_NUB);
                }
            });
            imageButtonEmployeeId.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_EMPLOYEE_ID);
                }
            });
            imageButtonStartTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_START_TIME);
                }
            });
            imageButtonEndTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_END_TIME);
                }
            });
            imageButtonLeaderId.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(SignQueryActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_LEADER_ID);
                }
            });
        }else{
            setContentView(R.layout.activity_sign_query);
        }

        DialogUIUtils.init(this);

        llSearch = (LinearLayout) findViewById(R.id.llSearch);
        linearLayout8 = (LinearLayout) findViewById(R.id.linearLayout1);
        textView1 = (TextView) findViewById(R.id.textView1);
        linearLayout2 = (LinearLayout) findViewById(R.id.linearLayout2);
        llSearch = (LinearLayout) findViewById(R.id.llSearch);
        linearLayout8 = (LinearLayout) findViewById(R.id.linearLayout1);
        textView1 = (TextView) findViewById(R.id.textView1);
        linearLayout2 = (LinearLayout) findViewById(R.id.linearLayout2);
        lblEmployeeId = (TextView) findViewById(R.id.lblEmployeeId);
        txtEmployeeId = (EditText) findViewById(R.id.txtEmployeeId);
        txtLeaderId = (EditText) findViewById(R.id.txtLeaderId);
        lblDocNub = (TextView) findViewById(R.id.lblDocNub);
        txtDocNub = (EditText) findViewById(R.id.txtDocNub);
        lblDocName = (TextView) findViewById(R.id.lblDocName);
        txtDocName = (EditText) findViewById(R.id.txtDocName);
        linearLayout3 = (LinearLayout) findViewById(R.id.linearLayout3);
        lblStartTime = (TextView) findViewById(R.id.lblStartTime);
        txtStartTime = (EditText) findViewById(R.id.txtStartTime);
        lblEndTime = (TextView) findViewById(R.id.lblEndTime);
        txtEndTime = (EditText) findViewById(R.id.txtEndTime);
        btnClear = (Button) findViewById(R.id.btnClear);
        btnSerach = (Button) findViewById(R.id.btnSerach);
        btnClose = (Button) findViewById(R.id.btnClosed);
        lvSign = (ListView) findViewById(R.id.lvSign);

        FragmentManager fragmentManager = getSupportFragmentManager();
        mSignDataFragment = (SignDataFragment) fragmentManager.findFragmentByTag("data");
        if (mSignDataFragment == null) {
            mSignDataFragment = new SignDataFragment();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(mSignDataFragment, "data");
            transaction.commit();
        }
        signList = collectLoadedData();
        if (signList == null) {

        }else{
            SignAdapter signAdapter = new SignAdapter(SignQueryActivity.this, signList);
            lvSign.setAdapter(signAdapter);
        }

        Intent intent = getIntent();
        webServiceUrl = intent.getStringExtra("webServiceUrl");
        docName = intent.getStringExtra("docName");
        docNumber = intent.getStringExtra("docNumber");
        txtStartTime.setInputType(InputType.TYPE_NULL);
        txtEndTime.setInputType(InputType.TYPE_NULL);
        txtStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(SignQueryActivity.this, 0, new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        txtStartTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                        yearSart = year;
                        monthStart = month;
                        dayStart = dayOfMonth;


                    }
                }, mYear, mMonth, mDay).show();
            }
        });

        txtStartTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Calendar ca = Calendar.getInstance();
                    int mYear = ca.get(Calendar.YEAR);
                    int mMonth = ca.get(Calendar.MONTH);
                    int mDay = ca.get(Calendar.DAY_OF_MONTH);
                    new DatePickerDialog(SignQueryActivity.this, 0, new OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            txtStartTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                            yearSart = year;
                            monthStart = month;
                            dayStart = dayOfMonth;

                        }
                    }, mYear, mMonth, mDay).show();
                }
            }
        });

        txtEndTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Calendar ca = Calendar.getInstance();
                    int mYear = ca.get(Calendar.YEAR);
                    int mMonth = ca.get(Calendar.MONTH);
                    int mDay = ca.get(Calendar.DAY_OF_MONTH);
                    new DatePickerDialog(SignQueryActivity.this, 0, new OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            txtEndTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                            yearEnd = year;
                            monthEnd = month;
                            dayEnd = dayOfMonth;
                        }
                    }, mYear, mMonth, mDay).show();
                }
            }
        });

        txtEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(SignQueryActivity.this, 0, new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        txtEndTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                        yearEnd = year;
                        monthEnd = month;
                        dayEnd = dayOfMonth;
                    }
                }, mYear, mMonth, mDay).show();
            }
        });

        btnSerach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request();
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtDocName.setText(StringUtils.EMPTY);
                txtDocNub.setText(StringUtils.EMPTY);
                txtEmployeeId.setText(StringUtils.EMPTY);
                txtStartTime.setText(StringUtils.EMPTY);
                txtEndTime.setText(StringUtils.EMPTY);
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }


    private void request() {
        final Dialog bean = DialogUIUtils.showLoading(SignQueryActivity.this, "Querying, please wait a moment...", false, false, false, false).show();
        String startTime = StringUtils.EMPTY;
        if (yearSart != -1 && monthStart != -1 && dayStart != -1) {
            Calendar ca = Calendar.getInstance();
            ca.set(yearSart, monthStart, dayStart, 0, 0, 0);
            SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startTime = formater.format(ca.getTime());
        }
        String endTime = StringUtils.EMPTY;
        if (yearEnd != -1 && monthEnd != -1 && dayEnd != -1) {
            Calendar ca = Calendar.getInstance();
            ca.set(yearEnd, monthEnd, dayEnd, 23, 59, 59);
            SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            endTime = formater.format(ca.getTime());
        }

        SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
        map.put("Documentname", txtDocName.getText().toString());
        map.put("Documentnumber", txtDocNub.getText().toString());
        map.put("Employeeid", txtEmployeeId.getText().toString());
        map.put("Leaderid", txtLeaderId.getText().toString());
        map.put("StartTime", startTime);
        map.put("EndTime", endTime);
//        map.put("Documentname", "");
//        map.put("Documentnumber", "663");
//        map.put("EmployeeId", "");
//        map.put("StartTime", "");
//        map.put("EndTime", "");
        WebServiceUtil.call(webServiceUrl, "GetSignDetail", map, new WebServiceUtil.ResponseCallBack() {
            @Override
            public void onSuccess(Object result) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("userName", txtUser.getText().toString());
//                intent.putExtra("userPassword", txtPwd.getText().toString());
//                intent.putExtra("webServiceUrl", url);
//
//                intent.putExtra("pdfUrl", pdfUrl);
//
//                startActivity(intent);
                SoapObject soapresult = (SoapObject) result;
                signList = new ArrayList<>();
                int count = soapresult.getPropertyCount();
                for (int i = 0; i < count; i++) {
                    SoapObject soapresult1 = (SoapObject) soapresult.getProperty(i);
                    SignItem signItem = new SignItem();
                    try {
                        signItem = SoapObjectUtil.soapToPojo(SignItem.class, soapresult1);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                    signList.add(signItem);
                }
                SignAdapter signAdapter = new SignAdapter(SignQueryActivity.this, signList);
                lvSign.setAdapter(signAdapter);
                DialogUIUtils.dismiss(bean);
            }

            @Override
            public void onError(String e) {

                DialogUIUtils.dismiss(bean);
                SmileDialog dialog = new SmileDialogBuilder(SignQueryActivity.this, SmileDialogType.ERROR)
                        .setContentText(e)
                        .setTitleText("Error message")
                        .build();
                dialog.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        mSignDataFragment.setSignList(signList);
        super.onDestroy();
    }

    private List<SignItem> collectLoadedData() {
        return mSignDataFragment.getSignList();
    }

    // 扫码界面回调方法
    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch(requestCode) {
            case REQUEST_CODE_DOC_NAME:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtDocName.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_DOC_NUB:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtDocNub.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_EMPLOYEE_ID:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtEmployeeId.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_START_TIME:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtStartTime.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_END_TIME:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtEndTime.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_LEADER_ID:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtLeaderId.setText(CameraScan.parseScanResult(data));
                }
                break;
        }
    }
}
